package com.anycc.cloud.core.service.impl;

import com.anycc.cloud.core.dto.EchartsDataDto;
import com.anycc.cloud.core.entity.Account;
import com.anycc.cloud.core.entity.Role;
import com.anycc.cloud.core.repository.*;
import com.anycc.cloud.core.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * index service impl
 */
@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private ModuleRepository moduleRepository;
    @Autowired
    private OrgRepository orgRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private RoleRepository roleRepository;


    @Override
    public List<EchartsDataDto> getEurekaInstancesAmount() {
        List<EchartsDataDto> indexDataDtoList = new ArrayList<>();
        Map<String, List<ServiceInstance>> serviceInstanceMap = new HashMap<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> serviceInstances = discoveryClient.getInstances(service);
            serviceInstanceMap.put(service, serviceInstances);
        }
        System.out.println(serviceInstanceMap);
        serviceInstanceMap.forEach((k, v) ->
                indexDataDtoList.add(new EchartsDataDto(k, v.size()))
        );
        return indexDataDtoList;
    }

    @Override
    public List<EchartsDataDto> getAccountUserRatio() {
        List<EchartsDataDto> indexDataDtoList = new ArrayList<>();
        List<Role> roleList = roleRepository.findAll();
        roleList.forEach(role -> {
            List<Account> roleAccount = accountRepository.findAll().stream().filter(
                    account -> account.getRoles().contains(role)).collect(Collectors.toList());
            indexDataDtoList.add(
                    new EchartsDataDto(role.getName(),roleAccount.size()));
        });
        return indexDataDtoList;
    }

    @Override
    public List<EchartsDataDto> getEntityAccountList() {
        List<EchartsDataDto> indexDataDtoList = new ArrayList<>();
        indexDataDtoList.add(new EchartsDataDto("accountNum", accountRepository.findAll().size()));
        indexDataDtoList.add(new EchartsDataDto("moduleNum", moduleRepository.findAll().size()));
        indexDataDtoList.add(new EchartsDataDto("orgNum", orgRepository.findAll().size()));
        indexDataDtoList.add(new EchartsDataDto("areaNum", areaRepository.findAll().size()));
        return indexDataDtoList;
    }

}
